import axios from 'axios'
import qs from 'qs'

const TIME_OUT = 30000;
axios.defaults.baseURL = "http://127.0.0.1:8081"
// 请求数据拦截处理
axios.interceptors.request.use(config => {
// code... 你的逻辑
  return config
}, error => {
  return Promise.reject(error)
})

// 返回数据拦截处理
axios.interceptors.response.use(response => {
  //code... 你的逻辑
  return response.data //直接返回后台返回的json object
}, error => Promise.reject(error.response))

/*
* 封装一个私有的请求方法
*/
const _request = (method, url, data) => {
  const headers = {
    'access_token': window.localStorage.getItem('access_token'),
    'Content-Type': ''
  }
  const configData = {
    url, // 请求的地址
    timeout: TIME_OUT, // 超时时间, 单位毫秒
    headers
  }

  if (method === 'get') {
    configData.method = 'get'
    configData.params = data// get 请求的数据
  } else if (method === 'postForm') {
    configData.method = 'post'
    configData.headers['Content-Type'] = 'application/x-www-form-urlencoded'
    configData.data = qs.stringify(data)
  } else if (method === 'postJson') {
    configData.method = 'post'
    configData.headers['Content-Type'] = 'application/json; charset=utf8'
    configData.data = data
  }
  return axios(configData)
}

class Ajax {
  get = (url, data = {}) => {
    return _request('get', url, data)
  }

  postForm = (url, data = {}) => {
    return _request('postForm', url, data)
  }

  postJson = (url, data = {}) => {
    return _request('postJson', url, data)
  }

  post = this.postJson // 默认post的Content-Type是application/json
}

export default new Ajax()
